from fastapi import APIRouter, Request, Depends,HTTPException
from jose import JWTError, jwt
from odoo.addons.fastapi_odoo_bridge.core.token import SECRET_KEY, ALGORITHM
from ...web_api.exceptions.http_exception import AuthException
from starlette.status import HTTP_401_UNAUTHORIZED

"""
拦截函数
"""

async def auth_request_handler(request: Request):
    """
    调度函数，用于处理每个请求。
    """
    # 指定需要鉴权的路径前缀
    protected_paths = ['/user_route']

    # 检查请求路径是否需要鉴权
    if any([path in str(request.url) for path in protected_paths]):
        # 获取请求头中的Token
        if '/user_route/pop_up/check/success' in str(request.url):
            auth_token = request.query_params.get('Authorization')
        else:
            auth_token = request.headers.get('Authorization')
        # 如果Token不存在，返回未授权响应
        if not auth_token:
             raise AuthException(status_code=HTTP_401_UNAUTHORIZED, detail='用户未登录',code=HTTP_401_UNAUTHORIZED)
        # 尝试解析Token
        try:
            payload = jwt.decode(auth_token, SECRET_KEY, algorithms=[ALGORITHM])
        except jwt.ExpiredSignatureError:
            # Token过期
            raise AuthException(status_code=HTTP_401_UNAUTHORIZED, detail='Token 过期',code=HTTP_401_UNAUTHORIZED)
        except jwt.JWTError:
            raise AuthException(status_code=HTTP_401_UNAUTHORIZED, detail='Token 无效',code=HTTP_401_UNAUTHORIZED)


class AuthRouter(APIRouter):
    def add_api_route(self, path: str, endpoint, **kwargs):
        """
        给单独需要校验token的路由进行添加依赖
        """
        if 'dependencies' not in kwargs or kwargs['dependencies'] is None:
            kwargs['dependencies'] = []
        kwargs['dependencies'].append(Depends(auth_request_handler))
        super().add_api_route(path, endpoint, **kwargs)
